//
//  AppDelegate.m
//  YMIMDemo
//
//  Created by reyzhang on 2022/5/24.
//
#import "AppDelegate.h"
#import <YMIMKit/YMIMKit.h>
#import "LoginViewController.h"
#import "MainTabBarController.h"
#import <GTSDK/GeTuiSdk.h>     // GetuiSdk头文件
#import "ChatConversationViewController.h"
#import <MJExtension/MJExtension.h>

@interface AppDelegate () <YMConnectionStatusDelegate,GeTuiSdkDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = [UIColor whiteColor];
    
    
    NSAssert(kYMAppKey.length > 0, @"请先配置译码小二郎 AppKey");
    NSAssert(kYMAppSecret.length > 0, @"请先配置译码小二郎 AppSecret");
    
    
    //1. SDK初始化
    YMIMConfig *config = [YMIMConfig configWithAppkey:kYMAppKey appsecret:kYMAppSecret];
    
    //开启日志输出
    config.enableConsoleLog = YES;
    [[YMIMClient sharedClient] initSDKWithConfig:config];
    
    //2. IM状态监听回调
    [YMIMClient sharedClient].connectionStatusDelegate = self;
  
    
    [[UINavigationBar appearance] setBackgroundImage:[YMIMKitUtils imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    [self showLoginVC];
    [self.window makeKeyAndVisible];
    
    // 通过个推平台分配的appId、 appKey 、appSecret 启动SDK，注：该方法需要在主线程中调用
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self launchingOptions:nil];
    // 注册远程通知
    [GeTuiSdk registerRemoteNotification: (UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionBadge)];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(enterMain:) name:@"enterMain" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showLoginVC) name:@"login" object:nil];
  
    
    return YES;
}
/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    //个推SDK已注册，返回clientId
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setValue:clientId forKey:@"ClientId"];
    [userDefaults synchronize];
    NSLog(@"\n>>>[GeTuiSdk RegisterClient]:%@\n\n", clientId);
}

/// 通知展示（iOS10及以上版本）
/// @param center center
/// @param notification notification
/// @param completionHandler completionHandler
- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification completionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APNs] %@ \n%@", NSStringFromSelector(_cmd), notification.request.content.userInfo];
//    [self.homePage logMsg:msg];
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要，判断是否要提示用户Badge、Sound、Alert等
    //completionHandler(UNNotificationPresentationOptionNone); 若不显示通知，则无法点击通知
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

/// 收到通知信息
/// @param userInfo apns通知内容
/// @param center UNUserNotificationCenter（iOS10及以上版本）
/// @param response UNNotificationResponse（iOS10及以上版本）
/// @param completionHandler 用来在后台状态下进行操作（iOS10以下版本）
- (void)GeTuiSdkDidReceiveNotification:(NSDictionary *)userInfo notificationCenter:(UNUserNotificationCenter *)center response:(UNNotificationResponse *)response fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    NSString *gid = [NSString stringWithFormat:@"%@",  [userInfo valueForKey:@"gid"]];
    NSString *conversationType = [NSString stringWithFormat:@"%@",[userInfo valueForKey:@"conversationType"]];
    NSString *title = [NSString stringWithFormat:@"%@",[userInfo valueForKey:@"title"]];
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [userDefaults valueForKey:@"token"];
    if (token == nil||[token isEqualToString:@""]) {
        
     
    }else{
        
        MainTabBarController *tabVC = (MainTabBarController *)[UIApplication sharedApplication].delegate.window.rootViewController;
        NSArray *views = tabVC.viewControllers;
        int count = 0;
        for(id VC in views)
        {
            count++;
            if (count==1) {
                
                UINavigationController *nav = (UINavigationController *)VC;
                ChatConversationViewController *vc = [[ChatConversationViewController alloc] initWithConversationType:[conversationType intValue] targetId:gid];
                vc.hidesBottomBarWhenPushed = YES;
                vc.title = title;
                [nav pushViewController:vc animated:YES];
        
            }
 
        }
   
    }
    

    
    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}


/// 收到透传消息
/// @param userInfo    推送消息内容
/// @param fromGetui   YES: 个推通道  NO：苹果apns通道
/// @param offLine     是否是离线消息，YES.是离线消息
/// @param appId       应用的appId
/// @param taskId      推送消息的任务id
/// @param msgId       推送消息的messageid
/// @param completionHandler 用来在后台状态下进行操作（通过苹果apns通道的消息 才有此参数值）
- (void)GeTuiSdkDidReceiveSlience:(NSDictionary *)userInfo fromGetui:(BOOL)fromGetui offLine:(BOOL)offLine appId:(NSString *)appId taskId:(NSString *)taskId msgId:(NSString *)msgId fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // [ GTSDK ]：汇报个推自定义事件(反馈透传消息)，开发者可以根据项目需要决定是否使用, 非必须
    // [GeTuiSdk sendFeedbackMessage:90001 andTaskId:taskId andMsgId:msgId];
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [APN] %@ \nReceive Slience: fromGetui:%@ appId:%@ offLine:%@ taskId:%@ msgId:%@ userInfo:%@ ", NSStringFromSelector(_cmd), fromGetui ? @"个推消息" : @"APNs消息", appId, offLine ? @"离线" : @"在线", taskId, msgId, userInfo];
//    [self.homePage logMsg:msg];

    if(completionHandler) {
        // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
        completionHandler(UIBackgroundFetchResultNoData);
    }
}

- (void)GeTuiSdkNotificationCenter:(UNUserNotificationCenter *)center openSettingsForNotification:(UNNotification *)notification {
    // [ 参考代码，开发者注意根据实际需求自行修改 ] 根据APP需要自行修改参数值
}


- (void)GeTuiSdkDidOccurError:(NSError *)error {
    NSString *msg = [NSString stringWithFormat:@"[ TestDemo ] [GeTuiSdk GeTuiSdkDidOccurError]:%@\n\n",error.localizedDescription];

    // SDK发生错误时，回调异常错误信息
    NSLog(@"%@", msg);
}


- (void)showLoginVC {

    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *token = [userDefaults valueForKey:@"token"];
    if (token == nil||[token isEqualToString:@""]) {
        
        LoginViewController *vc = [[LoginViewController alloc]init];
        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
        self.window.rootViewController = nav;
        
    }else{
        
        [self autoLoginAction];
        MainTabBarController *tabVC = [[MainTabBarController alloc] init];
        self.window.rootViewController = tabVC;
        
      
    }

 
}

-(void)autoLoginAction{
   
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *info = [userDefaults valueForKey:@"userInfo"];
    
    NSString *avatarStr = [NSString stringWithFormat:@"%@",[info valueForKey:@"userAvatar"]];
    NSString *uid = [NSString stringWithFormat:@"%@",[info valueForKey:@"uid"]];
    NSString *username = [NSString stringWithFormat:@"%@",[info valueForKey:@"username"]];
    NSMutableDictionary *params = @{}.mutableCopy;
    params[@"uid"] = uid;
    params[@"username"] = username;
    params[@"userAvatar"] = avatarStr;
    params[@"appKey"] = kYMAppKey;
    params[@"appSecret"] = kYMAppSecret;


    [YMNetworkUtils postjson:@"https://im.yimaxiaoerlang.cn/chat/login" parameters:params succes:^(NSDictionary * _Nonnull dic) {
        //get token
        NSString *token = dic[@"data"][@"token"];

        YMUserInfo *userInfo = [YMUserInfo mj_objectWithKeyValues:dic[@"data"]];
        [[YMIMClient sharedClient] setUserInfo:userInfo];

        //save info
        [[NSUserDefaults standardUserDefaults] setObject:[userInfo mj_JSONObject] forKey:@"userInfo"];
        [[NSUserDefaults standardUserDefaults] setObject:token forKey:@"token"];
        [[NSUserDefaults standardUserDefaults] synchronize];

        //IM连接
        [self connectIMWithToken:token uid:uid];
        
        //绑定推送信息
        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
        NSString *clientId = [userDefaults valueForKey:@"ClientId"];
        [[YMIMClient sharedClient] bindPushGTClientId:clientId withUserId:uid completion:^(YMErrorCode code) {

            NSLog(@"%ld===",(long)code);

        }];

    } failure:^(NSError * _Nonnull error) {
        NSLog(@"error:%@",error);
    }];
}



- (void)connectIMWithToken:(NSString *)token uid:(NSString *)uid {
    
    //im 连接
    [[YMIMClient sharedClient] loginWithToken:token completion:^(YMConnectStatusCode code) {
        if (code == YMConnectSuccess) {
            
        }else {
            NSLog(@"error code :%ld",(long)code);
        }
    }];
}


- (void)onYMConnectionStatusChanged:(YMConnectStatusCode)status {
    
    if (status == YMConnectInvalidTokenOrTokenExpired) {
        [[YMIMClient sharedClient] logout];
    }else if (status == YMConnectUserLoginOnAnotherDevice) {
        [YMIMKitUtils showAlertWithTitle:@"" message:@"账号在另外一个设备上登录" from:self.window.rootViewController showCancel:NO confirmHandler:^{
            [[YMIMClient sharedClient] logout];
            [self showLoginVC];
        }];
    }
}




- (void)enterMain:(NSNotification *)notif {
    
    MainTabBarController *tabVC = [[MainTabBarController alloc] init];
    self.window.rootViewController = tabVC;
}

@end
